/**
 * 自动搜索
 * @props   {String}   vlaue     false
 */
import React from 'react';
import { TreeSelect } from 'antd';
import debounce from 'lodash/debounce';
import { isObject, looseEqual } from 'utils/share';
import './selectAccount.less';

const TreeNode = TreeSelect.TreeNode;
const defaultPlaceholder = '请输入搜索字段';


class AutoCompletePlate extends React.Component {
  constructor(props) {
    super(props);
    const value = props.value || undefined;
    this.state = {
      value: value && value.toString(),
      dataSource: props.preData || [],
      disabled: props.disabled,
      searchParams: props.searchParams || []
    };
    this.onSearch = debounce(this.onSearch.bind(this), 500);
    this.renderNode = this.renderNode.bind(this);
    this.onSelect = this.onSelect.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  componentDidMount() {
    const { preSearch = false, preFetchList, searchParams } = this.props;
    if (preSearch && !searchParams) {
      preFetchList(searchParams);
    }
  }

  componentWillReceiveProps(nextProps) {
    const { preSearch = false, preFetchList, handleClear } = this.props;
    const dataSource = nextProps.dataSource;
    const searchParams = nextProps.searchParams;
    if ('value' in nextProps) {
      const value = nextProps.value || undefined;
      this.setState({ value: value && value.toString() });
    }
    if (dataSource) {
      this.setState({ dataSource });
    }
    if (dataSource.length === 0 && handleClear) {
      this.setState({ value: '' });
    }
    if (searchParams && !looseEqual(searchParams, this.state.searchParams) && preSearch) {
      preFetchList(searchParams);
      this.setState({ searchParams });
    }
    if (nextProps.disabled !== this.props.disabled) {
      this.setState({ disabled: nextProps.disabled });
    }
  }
  // 输入框搜索
  onSearch(val) {
    const value = val.replace(/\s+/g, '');
    const { fetchList, searchParams, searchKey, result = false,
      filterRequest, notFind } = this.props;
    this.setState({ value: '' });
    if (!fetchList) {
      return;
    }
    if (filterRequest && !filterRequest(value)) {
      return;
    }
    fetchList({ [searchKey]: value, ...searchParams }).then((content) => {
      const datas = result ? result(content) : content;
      if (Array.isArray(content) && content.length === 0) {
        notFind && notFind();
      }
      this.setState({
        dataSource: datas || []
      });
    });
  }
  // 被选中回调
  onSelect(value) {
    const { dataSource } = this.state;
    const params = dataSource.find(item => item.id === +value);
    const { handleSelect, onSelect, onChange, searchParams } = this.props;
    onChange(params.id);
    if (handleSelect) {
      handleSelect(params).then((content) => {
        this.setState({
          value: content.id
        });
        onSelect && onSelect(content);
      });
    } else {
      this.setState({
        value: params.id
      });
      onSelect && onSelect(params, searchParams);
    }
  }
  onChange(value) {
    const { onSelect, searchParams } = this.props;
    if (!value) {
      this.setState({
        value: ''
      });
      onSelect && onSelect({}, searchParams);
    }
  }

  renderNode() {
    const { keys = [], itemRender } = this.props;
    const { dataSource } = this.state;
    return dataSource.map((item) => {
      const title = itemRender ? itemRender(item) : keys.map(row => isObject(row) ?
        <span className="search-item" key={row.key}>{row.render(item[row.key], item)}</span>
        : <span className="search-item" key={row}>{item[row]}</span>);
      return (<TreeNode
        value={`${item.id}`}
        title={<React.Fragment>{title}</React.Fragment>}
        key={item.id}
      />);
    });
  }

  render() {
    const { placeholder, showSearch = true, style,
      index = '' } = this.props;
    const { disabled = false } = this.state;
    const treeNode = this.renderNode();
    return (
      <TreeSelect
        {...this.props}
        key={index}
        disabled={!!disabled}
        style={style}
        onSearch={this.onSearch}
        onSelect={this.onSelect}
        showSearch={showSearch}
        value={this.state.value}
        filterTreeNode={() => true}
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        placeholder={placeholder || defaultPlaceholder}
        dropdownClassName={'selectAccount'}
        allowClear
        treeDefaultExpandAll
        onChange={this.onChange}
      >
        {treeNode}
      </TreeSelect>
    );
  }
}
export default AutoCompletePlate;
